<?php
class Services_Ebay_Case_Response extends QDB_ActiveRecord_Abstract
{
	/**
	 * 返回对象的定义
	 *
	 * @static
	 *
	 * @return array
	 */
	static function __define()
	{
		return array
		(
			// 指定该 ActiveRecord 要使用的行为插件
			'behaviors' => '',

			// 指定行为插件的配置
			'behaviors_settings' => array
			(
			    # '插件名' => array('选项' => 设置),
			),

			// 用什么数据表保存对象
			'table_name' => 'services_ebay_case_response',

			// 指定数据表记录字段与对象属性之间的映射关系
			// 没有在此处指定的属性，QeePHP 会自动设置将属性映射为对象的可读写属性
			'props' => array
			(
				// 主键应该是只读，确保领域对象的“不变量”
				'id' => array('readonly' => true),

				/**
				 *  可以在此添加其他属性的设置
				 */
				# 'other_prop' => array('readonly' => true),

				/**
				 * 添加对象间的关联
				 */
				# 'other' => array('has_one' => 'Class'),

			),

			/**
			 * 允许使用 mass-assignment 方式赋值的属性
			 *
			 * 如果指定了 attr_accessible，则忽略 attr_protected 的设置。
			 */
			'attr_accessible' => '',

			/**
			 * 拒绝使用 mass-assignment 方式赋值的属性
			 */
			'attr_protected' => 'id',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值不允许由外部提供
			 *
			 * 这里指定的属性会在创建记录时被过滤掉，从而让数据库自行填充值。
			 */
			'create_reject' => '',

			/**
			 * 指定更新数据库中的对象时，哪些属性的值不允许由外部提供
			 */
			'update_reject' => '',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 如果填充值为 self::AUTOFILL_TIMESTAMP 或 self::AUTOFILL_DATETIME，
			 * 则会根据属性的类型来自动填充当前时间（整数或字符串）。
			 *
			 * 如果填充值为一个数组，则假定为 callback 方法。
			 */
			'create_autofill' => array
			(
				# 属性名 => 填充值
				# 'is_locked' => 0,
			),

			/**
			 * 指定更新数据库中的对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 填充值的指定规则同 create_autofill
			 */
			'update_autofill' => array
			(
			),

			/**
			 * 在保存对象时，会按照下面指定的验证规则进行验证。验证失败会抛出异常。
			 *
			 * 除了在保存时自动验证，还可以通过对象的 ::meta()->validate() 方法对数组数据进行验证。
			 *
			 * 如果需要添加一个自定义验证，应该写成
			 *
			 * 'title' => array(
			 *	array(array(__CLASS__, 'checkTitle'), '标题不能为空'),
			 * )
			 *
			 * 然后在该类中添加 checkTitle() 方法。函数原型如下：
			 *
			 * static function checkTitle($title)
			 *
			 * 该方法返回 true 表示通过验证。
			 */
			'validations' => array
			(
			),
		);
	}


/* ------------------ 以下是自动生成的代码，不能修改 ------------------ */

	/**
	 * 开启一个查询，查找符合条件的对象或对象集合
	 *
	 * @static
	 *
	 * @return QDB_Select
	 */
	static function find()
	{
		$args = func_get_args();
		return QDB_ActiveRecord_Meta::instance(__CLASS__)->findByArgs($args);
	}

	/**
	 * 返回当前 ActiveRecord 类的元数据对象
	 *
	 * @static
	 *
	 * @return QDB_ActiveRecord_Meta
	 */
	static function meta()
	{
		return QDB_ActiveRecord_Meta::instance(__CLASS__);
	}


/* ------------------ 以上是自动生成的代码，不能修改 ------------------ */

	static function create($response)
	{
		foreach ($response as $r)
		{
			$response = Services_Ebay_Case_Response::find('services_ebay_case_id=? and author_role=? and response_time=?', $r['services_ebay_case_id'], $r['author_role'], $r['response_time'])->asArray()->getOne();
			if (! $response)
			{
				$response = new Services_Ebay_Case_Response();
				$response->services_ebay_case_id = $r['services_ebay_case_id'];
				$response->author_role = $r['author_role'];
				$response->description = $r['description'];
				$response->shipping_carrier = empty($r['shipping_carrier']) ? '' : $r['shipping_carrier'];
				$response->tracking_number = empty($r['tracking_number']) ? '' : $r['tracking_number'];
				$response->shipped_time = empty($r['shipped_time']) ? NULL : $r['shipped_time'];
				$response->refund = empty($r['refund']) ? NULL : $r['refund'];
				$response->refund_transaction_id =  empty($r['refund_transaction_id']) ? '' : $r['refund_transaction_id'];
				$response->message = $r['message'];
				$response->response_time = $r['response_time'];
				$response->save();
			}
		}
		return array('ack' => SUCCESS, 'message' => '');
	}
	
	static function provideShippingInfo($response)
	{
		if (! empty($response['shipping_carrier']) && ! empty($response['shipped_time']))
		{
			$case = Services_Ebay_Case::find('id=?', $response['services_ebay_case_id'])->asArray()->getOne();
			$token = Shop_API_Ebay::find('shop_id=?', $case['shop_id'])->asArray()->getOne();
			if ($token && $case)
			{
				$header = array(
					'X-EBAY-SOA-SECURITY-TOKEN: ' . $token['token'],
					'X-EBAY-SOA-OPERATION-NAME: provideShippingInfo'
				);
				$xml ='<?xml version="1.0" encoding="utf-8"?>';
				$xml .='<provideShippingInfoRequest xmlns="http://www.ebay.com/marketplace/resolution/v1/services">';
				$xml .='  <carrierUsed>' . $response['shipping_carrier'] . '</carrierUsed>';
				$xml .='  <caseId>';
				$xml .='    <id>' . $case['case_id'] . '</id>';
				$xml .='    <type>' . Helper_BSS_Normal::getIniOne('services_ebay_case_type', 'value', $case['type'], 'name') . '</type>';
				$xml .='  </caseId>';
				$xml .='  <comments>' . $response['message'] . '</comments>';
				$xml .='  <shippedDate>' . date('c', strtotime($response['shipped_time'])) . '</shippedDate>';
				$xml .='</provideShippingInfoRequest>';
				$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_case_uri'), $header, $xml, 'provideShippingInfo');
				if ($result['ack'] == SUCCESS)
				{
					$response = simplexml_load_string($result['data']);
					if ($response && $response->ack == 'Success')
					{
						return array('ack' => SUCCESS, 'message' => '');
					}
					else
					{
						return array('ack' => FAILURE, 'message' => isset($response->errorMessage[0]->error[0]->message[0]) ? (string)$response->errorMessage[0]->error[0]->message[0] : '');
					}
				}
				else
				{
					return array('ack' => FAILURE, 'message' => $result['message']);
				}
			}
		}
		return array('ack' => FAILURE, 'message' => '解决方案提供信息不完整');
	}
	
	static function provideTrackingInfo($response)
	{
		if (! empty($response['shipping_carrier']) && ! empty($response['tracking_number']))
		{
			$case = Services_Ebay_Case::find('id=?', $response['services_ebay_case_id'])->asArray()->getOne();
			$token = Shop_API_Ebay::find('shop_id=?', $case['shop_id'])->asArray()->getOne();
			if ($token && $case)
			{
				$header = array(
					'X-EBAY-SOA-SECURITY-TOKEN: ' . $token['token'],
					'X-EBAY-SOA-OPERATION-NAME: provideTrackingInfo'
				);
				$xml ='<?xml version="1.0" encoding="utf-8"?>';
				$xml .='<provideTrackingInfoRequest xmlns="http://www.ebay.com/marketplace/resolution/v1/services">';
				$xml .='  <carrierUsed>' . $response['shipping_carrier'] . '</carrierUsed>';
				$xml .='  <caseId>';
				$xml .='    <id>' . $case['case_id'] . '</id>';
				$xml .='    <type>' . Helper_BSS_Normal::getIniOne('services_ebay_case_type', 'value', $case['type'], 'name') . '</type>';
				$xml .='  </caseId>';
				$xml .='  <comments>' . $response['message'] . '</comments>';
				$xml .='  <trackingNumber>' . $response['tracking_number'] . '</trackingNumber>';
				$xml .='</provideTrackingInfoRequest>';
				$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_case_uri'), $header, $xml, 'provideTrackingInfo');
				if ($result['ack'] == SUCCESS)
				{
					$response = simplexml_load_string($result['data']);
					if ($response && $response->ack == 'Success')
					{
						return array('ack' => SUCCESS, 'message' => '');
					}
					else
					{
						return array('ack' => FAILURE, 'message' => isset($response->errorMessage[0]->error[0]->message[0]) ? (string)$response->errorMessage[0]->error[0]->message[0] : '');
					}
				}
				else
				{
					return array('ack' => FAILURE, 'message' => $result['message']);
				}
			}
		}
		return array('ack' => FAILURE, 'message' => '解决方案提供信息不完整');
	}
	
	static function offerOtherSolution($response)
	{
		if (! empty($response['message']))
		{
			$case = Services_Ebay_Case::find('id=?', $response['services_ebay_case_id'])->asArray()->getOne();
			$token = Shop_API_Ebay::find('shop_id=?', $case['shop_id'])->asArray()->getOne();
			if ($token && $case)
			{
				$header = array(
					'X-EBAY-SOA-SECURITY-TOKEN: ' . $token['token'],
					'X-EBAY-SOA-OPERATION-NAME: offerOtherSolution'
				);
				$xml ='<?xml version="1.0" encoding="utf-8"?>';
				$xml .='<offerOtherSolutionRequest xmlns="http://www.ebay.com/marketplace/resolution/v1/services">';
				$xml .='  <caseId>';
				$xml .='    <id>' . $case['case_id'] . '</id>';
				$xml .='    <type>' . Helper_BSS_Normal::getIniOne('services_ebay_case_type', 'value', $case['type'], 'name') . '</type>';
				$xml .='  </caseId>';
				$xml .='  <messageToBuyer>' . $response['message'] . '</messageToBuyer>';
				$xml .='</offerOtherSolutionRequest>';
				$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_case_uri'), $header, $xml, 'offerOtherSolution');
				if ($result['ack'] == SUCCESS)
				{
					$response = simplexml_load_string($result['data']);
					if ($response && $response->ack == 'Success')
					{
						return array('ack' => SUCCESS, 'message' => '');
					}
					else
					{
						return array('ack' => FAILURE, 'message' => isset($response->errorMessage[0]->error[0]->message[0]) ? (string)$response->errorMessage[0]->error[0]->message[0] : '');
					}
				}
				else
				{
					return array('ack' => FAILURE, 'message' => $result['message']);
				}
			}
		}
		return array('ack' => FAILURE, 'message' => '解决方案提供信息不完整');
	}
	
	static function issueFullRefund($response)
	{
		$case = Services_Ebay_Case::find('id=?', $response['services_ebay_case_id'])->asArray()->getOne();
		$token = Shop_API_Ebay::find('shop_id=?', $case['shop_id'])->asArray()->getOne();
		if ($token && $case)
		{
			$header = array(
				'X-EBAY-SOA-SECURITY-TOKEN: ' . $token['token'],
				'X-EBAY-SOA-OPERATION-NAME: issueFullRefund'
			);
			$xml ='<?xml version="1.0" encoding="utf-8"?>';
			$xml .='<issueFullRefundRequest xmlns="http://www.ebay.com/marketplace/resolution/v1/services">';
			$xml .='  <caseId>';
			$xml .='    <id>' . $case['case_id'] . '</id>';
			$xml .='    <type>' . Helper_BSS_Normal::getIniOne('services_ebay_case_type', 'value', $case['type'], 'name') . '</type>';
			$xml .='  </caseId>';
			if (! empty($response['message']))
			{
				$xml .='  <comments>' . $response['message'] . '</comments>';
			}
			$xml .='</issueFullRefundRequest>';
			$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_case_uri'), $header, $xml, 'issueFullRefund');
			if ($result['ack'] == SUCCESS)
			{
				$response = simplexml_load_string($result['data']);
				if ($response && $response->ack == 'Success')
				{
					return array('ack' => SUCCESS, 'message' => '');
				}
				else
				{
					$message = isset($response->errorMessage[0]->error[0]->message[0]) ? (' 错误信息：' . (string)$response->errorMessage[0]->error[0]->message[0]) : '';
					return array('ack' => FAILURE, 'message' => '错误标志：' . (isset($response->ack) ? (string)$response->ack : '') . $message);
				}
			}
			else
			{
				return array('ack' => FAILURE, 'message' => $result['message']);
			}
		}
	}
	
	static function offerPartialRefund($response)
	{
		if (! empty($response['amount']))
		{
			$case = Services_Ebay_Case::find('services_ebay_case.id=?', $response['services_ebay_case_id'])
				->joinLeft('currency', 'code as currency_code', 'currency.id=services_ebay_case.currency_id')
				->asArray()->getOne();
			$token = Shop_API_Ebay::find('shop_id=?', $case['shop_id'])->asArray()->getOne();
			if ($token && $case)
			{
				$header = array(
					'X-EBAY-SOA-SECURITY-TOKEN: ' . $token['token'],
					'X-EBAY-SOA-OPERATION-NAME: offerPartialRefund'
				);
				$xml ='<?xml version="1.0" encoding="utf-8"?>';
				$xml .='<offerPartialRefundRequest xmlns="http://www.ebay.com/marketplace/resolution/v1/services">';
				$xml .='  <amount currencyCode="'. $case['currency_code'] . '">' . $response['amount'] . '</amount>';
				$xml .='  <caseId>';
				$xml .='    <id>' . $case['case_id'] . '</id>';
				$xml .='    <type>' . Helper_BSS_Normal::getIniOne('services_ebay_case_type', 'value', $case['type'], 'name') . '</type>';
				$xml .='  </caseId>';
				if (! empty($response['message']))
				{
					$xml .='  <comments>' . $response['message'] . '</comments>';
				}
				$xml .='</offerPartialRefundRequest>';
				$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_case_uri'), $header, $xml, 'offerPartialRefund');
				if ($result['ack'] == SUCCESS)
				{
					$response = simplexml_load_string($result['data']);
					if ($response && $response->ack == 'Success')
					{
						return array('ack' => SUCCESS, 'message' => '');
					}
					else
					{
						$message = isset($response->errorMessage[0]->error[0]->message[0]) ? (' 错误信息：' . (string)$response->errorMessage[0]->error[0]->message[0]) : '';
						return array('ack' => FAILURE, 'message' => '错误标志：' . (isset($response->ack) ? (string)$response->ack : '') . $message);
					}
				}
				else
				{
					return array('ack' => FAILURE, 'message' => $result['message']);
				}
			}
		}
		return array('ack' => FAILURE, 'message' => '解决方案提供信息不完整');
	}
	
	static function offerRefundUponReturn($response)
	{
		$case = Services_Ebay_Case::find('id=?', $response['services_ebay_case_id'])->asArray()->getOne();
		$return_address = Q::ini('custom_flag/services_ebay_case_response_return_address/address1');
		$token = Shop_API_Ebay::find('shop_id=?', $case['shop_id'])->asArray()->getOne();
		if ($token && $case)
		{
			$header = array(
				'X-EBAY-SOA-SECURITY-TOKEN: ' . $token['token'],
				'X-EBAY-SOA-OPERATION-NAME: offerReturnUponReturn',
			);
			$xml ='<?xml version="1.0" encoding="utf-8"?>';
			$xml .= '<offerRefundUponReturnRequest xmlns="http://www.ebay.com/marketplace/resolution/v1/services">';
			$xml .=   '<caseId>';
			$xml .=     '<id>' . $case['case_id'] . '</id>';
			$xml .=     '<type>' . Helper_BSS_Normal::getIniOne('services_ebay_case_type', 'value', $case['type'], 'name') . '</type>';
			$xml .=   '</caseId>';
			$xml .=   '<address>';
			$xml .=     '<name>' . $return_address['name'] . '</name>';
			$xml .=     '<country>' . $return_address['country_code'] . '</country>';
			$xml .=     '<stateOrProvince>' . $return_address['state'] . '</stateOrProvince>';
			$xml .=     '<city>' . $return_address['city'] . '</city>';
			$xml .=     '<street1>' . $return_address['street1'] . '</street1>';
			$xml .=     '<postalCode>' . $return_address['postal'] . '</postalCode>';
			$xml .=   '</address>';
			$xml .= '</offerRefundUponReturnRequest>';
			$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_case_uri'), $header, $xml, 'offerReturnUponReturn');
			if ($result['ack'] == SUCCESS)
			{
				$response = simplexml_load_string($result['data']);
				if ($response && strtolower($response->ack) == 'success')
				{
					return array('ack' => SUCCESS, 'message' => '');
				}
				else
				{
					$message = isset($response->errorMessage[0]->error[0]->message[0]) ? (' 错误信息：' . (string)$response->errorMessage[0]->error[0]->message[0]) : '';
					return array('ack' => FAILURE, 'message' => '错误标志：' . (isset($response->ack) ? (string)$response->ack : '') . $message);
				}
			}
			else
			{
				return array('ack' => FAILURE, 'message' => $result['message']);
			}
		}
	}
}